package com.ruoyi.system.wnjk.listener;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

@Configuration
public class RedisKeyExpirationListener {

    @Autowired
    private RedisTemplate redisTemplate;

    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory factory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(factory);
        container.addMessageListener((message, pattern) -> {
            String expiredKey = new String(message.getBody());
            if (expiredKey.startsWith("order:")) {
                handleExpiredOrder(expiredKey);
            }
        }, new PatternTopic("__keyevent@0__:expired")); // 监听过期事件
        return container;
    }

    private void handleExpiredOrder(String orderKey) {
        String date = (String) redisTemplate.opsForHash().get(orderKey, "date");
        String period = (String) redisTemplate.opsForHash().get(orderKey, "period");

        // 回滚库存
        String inventoryKey = "inventory:" + date + ":" + period;
        redisTemplate.opsForHash().increment(inventoryKey, "available", 1);
    }
}